<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Queue;

class Manage extends Common
{
    /**
     * 列表示例
     * */
    public function listDemo()
    {
        $list = Db::name('menu')->paginate(2);
        $this->assign('list', $list);

        $this->assign('title', '列表示例');
        return $this->fetch();
    }

    /**
     * 列表导出示例
     * */
    public function exportListDemo()
    {
        $title = '文件名';
        $th = ['标题一', '标题二', '标题三'];
        $td = ['key1', 'key2', 'key3'];
        $data = [
            [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ], [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ]
        ];

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 表单示例
     * */
    public function formDemo()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            echo "<pre>";
            print_r($input);
            exit;
        }
        $this->assign('title', '表单示例');
        return $this->fetch();
    }

    /**
     * 视频分片上传示例
     * */
    public function uploadVideo()
    {
        $this->assign('title', '视频分片上传示例');
        return $this->fetch();
    }

    /**
     * 统计图示例
     * */
    public function chartDemo()
    {
        $this->assign('title', '统计图');
        return $this->fetch();
    }

    /**
     * 树形列表示例
     * */
    public function treeDemo()
    {
        return $this->fetch();
    }

    public function test()
    {
        return $this->view->fetch();
    }

    /**
     * 树状图原始demo
     * */
    public function tree()
    {
        $this->assign('title', 'test');
        return $this->fetch();
    }

    /**
     * iconfont
     * */
    public function iconfont()
    {
        $this->assign('title', 'iconfont');
        return $this->fetch();
    }

    /**
     * 文章分类列表
     * */
    public function articleTypeList()
    {
        $list = Db::name('article_type')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '文章分类列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章分类
     * */
    public function doArticleType()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];

            if (empty($name)) adminReturn(2, '请输入名称');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('article_type')->where($where)->count();
            if ($count > 0) adminReturn(2, '该分类已存在');

            $data = [
                'name' => $name
            ];

            if ($id > 0) {
                $res = Db::name('article_type')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑文章分类成功', url('articleTypeList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $res = Db::name('article_type')->insert($data);
                if ($res) {
                    adminReturn(1, '新增文章分类成功', url('articleTypeList'));
                } else {
                    adminReturn(2, '新增文章分类失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('article_type')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '文章分类');

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章分类
     * */
    public function delArticleType()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '分类ID缺失');

        $info = Db::name('article_type')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('article_type')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 问卷列表
     * */
    public function questionList()
    {
        $input = Request()->param();

        $id = session('id');
        $title = $input['title'];

        if (empty($id)) adminReturn(3, '请重新登录');

        $where['is_del'] = 0;
        if ($id != 1) $where['user_id'] = $id;
        if ($title) $where['title'] = ['LIKE', "%${title}%"];

        $list = Db::name('question')->where($where)->order('id desc')->paginate()->each(function ($val) {
            $answer_count = Db::name('plan')->where(['question_id' => $val['id'], 'is_del' => 0, 'is_complete' => 1])->sum('answer_count');
            $val['answer_count'] = $answer_count ? : 0;

            $val['user_rule'] = json_decode($val['user_rule'], true);

            // 存在任务，隐藏列表【设置问卷作答规则】【AI作答】按钮
            $plan_count = Db::name('plan')->where(['question_id' => $val['id'], 'is_del' => 0])->count();
            $val['plan_count'] = $plan_count ? : 0;

            return $val;
        });

        $this->assign('list', $list);
        $this->assign('title', '问卷列表');

        return $this->view->fetch();
    }

    /**
     * 新增问卷
     * */
    public function addQuestionBak()
    {
        $input = Request()->param();

        // 网页地址
        $url = $input['url'];

        if (empty($url)) apiReturn(2, '请输入问卷预览地址');

        if (preg_match('/\/vm\/([a-zA-Z0-9]+)\.aspx/', $url, $matches)) {
            $sign = $matches[1];
        } else {
            apiReturn(2, '问卷预览地址有误，请重新输入');
        }

        $count = Db::name('question')->where(['sign' => $sign, 'is_del' => 0])->count();
        if ($count) apiReturn(2, '问卷已存在，如需重新添加请删除已存在的问卷');

        if (strpos($url, 'www.wjx.cn') === false) apiReturn(2, '问卷预览地址有误，请重新输入');

        $html = getAiCurl($url);

        if ($html === false) apiReturn(2, '无法获取网页内容');

        // 检查 DOMDocument 类是否可用
        if (!class_exists('DOMDocument')) apiReturn(2, 'DOMDocument 类未找到。请启用 PHP 的 DOM 扩展。');

        // 初始化 DOMDocument 并加载 HTML
        $dom = new \DOMDocument();
        libxml_use_internal_errors(true);
        $loaded = $dom->loadHTML($html, LIBXML_NOERROR | LIBXML_NOWARNING);
        libxml_clear_errors();

        if (!$loaded) apiReturn(2, '无法解析 HTML 内容');

        // 使用 DOMXPath 来查询特定部分的内容
        $xpath = new \DOMXPath($dom);

        $title = $xpath->query('//*[@id="htitle"]')->item(0)->nodeValue;
        $title = trim($title);

        // 找到 id="fieldset1" 的部分
        $fieldset = $xpath->query('//*[@id="fieldset1"]')->item(0);

        if (!$fieldset) apiReturn('未找到 id="fieldset1" 的部分');

        $questions = [];

        // 查询所有的 "field" div
        foreach ($xpath->query('.//div[contains(@class, "field")]', $fieldset) as $fieldDiv) {
            // 获取问题的文本
            $questionDiv = $xpath->query('.//div[@class="field-label"]', $fieldDiv)->item(0);
            if (!$questionDiv) {
                continue; // 如果没有找到问题，跳过
            }
            $questionText = trim($questionDiv->textContent);

            // 初始化答案数组
            $answers = [];

            // 查找包含答案选项的 "ui-controlgroup" div
            $controlGroupDiv = $xpath->query('.//div[contains(@class, "ui-controlgroup")]', $fieldDiv)->item(0);
            if ($controlGroupDiv) {
                // 查找所有的 "div.label" 元素作为答案选项
                foreach ($xpath->query('.//div[@class="label"]', $controlGroupDiv) as $answerDiv) {
                    $answerText = trim($answerDiv->textContent);
                    if (!empty($answerText)) {
                        $answers[] = $answerText;
                    }
                }
            }

            // 将问题和答案加入数组
            $questions[] = [
                'question' => $questionText,
                'answers' => $answers
            ];
        }

        if ($questions) {
            $user_id = session('id');

            $data = [
                'user_id' => $user_id,
                'title' => $title,
                'url' => $url,
                'question' => json_encode($questions, JSON_UNESCAPED_UNICODE),
                'sign' => $sign,
                'user_rule' => '',
                'create_time' => time()
            ];
            $res = Db::name('question')->insert($data);
            if ($res) {
                apiReturn(1, '新增问卷成功');
            } else {
                apiReturn(2, '新增问卷失败');
            }
        } else {
            apiReturn(2, '新增问卷失败，请检查问卷预览地址是否正确');
        }
    }

    public function addQuestion()
    {
        $input = Request()->param();
        $url = $input['url'];

        if (empty($url)) apiReturn(2, '请输入问卷预览地址');
        if (preg_match('/\/vm\/([a-zA-Z0-9]+)\.aspx/', $url, $matches)) {
            $sign = $matches[1];
        } else {
            apiReturn(2, '问卷预览地址有误，请重新输入');
        }

        $count = Db::name('question')->where(['sign' => $sign, 'is_del' => 0])->count();
        if ($count) apiReturn(2, '问卷已存在，如需重新添加请删除已存在的问卷');

        if (strpos($url, 'www.wjx.cn') === false) apiReturn(2, '问卷预览地址有误，请重新输入');

        $html = getAiCurl($url);
        if ($html === false) apiReturn(2, '无法获取网页内容');

        if (!class_exists('DOMDocument')) apiReturn(2, 'DOMDocument 类未找到。请启用 PHP 的 DOM 扩展。');

        $dom = new \DOMDocument();
        libxml_use_internal_errors(true);
        $loaded = $dom->loadHTML($html, LIBXML_NOERROR | LIBXML_NOWARNING);
        libxml_clear_errors();
        if (!$loaded) apiReturn(2, '无法解析 HTML 内容');

        $xpath = new \DOMXPath($dom);
        $title = $xpath->query('//*[@id="htitle"]')->item(0)->nodeValue;
        $title = trim($title);
        $fieldset = $xpath->query('//*[@id="fieldset1"]')->item(0);
        if (!$fieldset) apiReturn('未找到 id="fieldset1" 的部分');

        $questions = [];
        $type = 0;
        foreach ($xpath->query('.//div[contains(@class, "field")]', $fieldset) as $fieldDiv) {
            $questionDiv = $xpath->query('.//div[@class="field-label"]', $fieldDiv)->item(0);
            if (!$questionDiv) {
                continue;
            }
            $questionText = trim($questionDiv->textContent);
            $answers = [];

            // 处理单选和多选
            $controlGroupDiv = $xpath->query('.//div[contains(@class, "ui-controlgroup")]', $fieldDiv)->item(0);
            if ($controlGroupDiv) {
                if ($controlGroupDiv->getElementsByTagName('input')->length > 0) {
                    if ($controlGroupDiv->getElementsByTagName('input')[0]->getAttribute('type') === 'radio') {
                        $type = 1; // 单选题
                    } elseif ($controlGroupDiv->getElementsByTagName('input')[0]->getAttribute('type') === 'checkbox') {
                        $type = 2; // 多选题
                    }
                }
                foreach ($xpath->query('.//div[@class="label"]', $controlGroupDiv) as $answerDiv) {
                    $answerText = trim($answerDiv->textContent);
                    if (!empty($answerText)) {
                        $answers[] = $answerText;
                    }
                }
            }

            // 处理下拉框
            $selectDiv = $xpath->query('.//select', $fieldDiv);
            if ($selectDiv->length > 0) {
                foreach ($xpath->query('.//option', $selectDiv->item(0)) as $option) {
                    $optionText = trim($option->textContent);
                    if ($optionText !== "请选择") {
                        $answers[] = $optionText;
                    }
                }
                $type = 4;
            }

            // 处理问答题
            $inputDiv = $xpath->query('.//div[contains(@class, "ui-input-text")]', $fieldDiv);
            if ($inputDiv->length > 0) {
                $answers = []; // 问答题
                $type = 3;
            }

            $questions[] = [
                'question' => $questionText,
                'answers' => $answers,
                'type' => $type
            ];
        }

        if ($questions) {
            $user_id = session('id');
            $data = [
                'user_id' => $user_id,
                'title' => $title,
                'url' => $url,
                'question' => json_encode($questions, JSON_UNESCAPED_UNICODE),
                'sign' => $sign,
                'user_rule' => '',
                'create_time' => time()
            ];
            $res = Db::name('question')->insert($data);
            if ($res) {
                apiReturn(1, '新增问卷成功');
            } else {
                apiReturn(2, '新增问卷失败');
            }
        } else {
            apiReturn(2, '新增问卷失败，请检查问卷预览地址是否正确');
        }
    }

    /**
     * 设置问卷作答规则
     * */
    public function setQuestionRule()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $all_answer_count = $input['all_answer_count'];
            $single_answer_time = $input['single_answer_time'];
            $user_rule = json_decode($input['user_rule'], true);

            if (empty($id)) apiReturn(2, 'ID缺失');
            if (empty($all_answer_count)) apiReturn(2, '请输入问卷作答数量');
            if ($all_answer_count < 1) apiReturn(2, '问卷作答数量至少1套');
            if (empty($single_answer_time)) apiReturn(2, '请输入单套问卷作答时长（秒）');
            if (!($single_answer_time >= 25 && $single_answer_time <= 30)) apiReturn(2, '单套问卷作答时长请设置在25~30秒区间');

            if (in_array('', $user_rule, true)) apiReturn(2, '请完善规则');

            $data = [
                'all_answer_count' => $all_answer_count,
                'single_answer_time' => $single_answer_time,
                'user_rule' => $input['user_rule'],
                'update_time' => time()
            ];

            $res = Db::name('question')->where(['id' => $id])->update($data);
            if ($res) {
                apiReturn(1, '保存成功');
            } else {
                apiReturn(2, '保存失败');
            }
        } else {
            $id = Request()->param('id');

            $info = Db::name('question')->where(['id' => $id])->find();
            $question = $info['question'];
            $info['question'] = json_decode($question, true);
            $info['user_rule'] = $info['user_rule'] ? json_decode($info['user_rule'], true) : [];

            $this->assign('title', '设置问卷作答规则');
            $this->assign('info', $info);
            $this->assign('question', $question);
            $this->assign('user_rule', json_encode($info['user_rule'], JSON_UNESCAPED_UNICODE));
            return $this->view->fetch();
        }
    }

    /**
     * AI作答
     * */
    public function aiAnswer()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('question')->where(['id' => $id, 'is_del' => 0])->find();
        if (empty($info)) adminReturn(2, '问卷不存在或已删除');
        if (empty($info['question']) || empty($info['sign'])) adminReturn(2, '问卷数据异常，请删除后重新新增');
        if ($info['all_answer_count'] == 0 || $info['single_answer_time'] == 0) adminReturn(2, '请设置设置问卷作答规则');

        // 检测是否还有未向AI发起请求的任务
        $no_start_plan_count = Db::name('plan')->where(['question_id' => $id, 'is_complete' => 0, 'is_del' => 0])->count();
        if ($no_start_plan_count) adminReturn(2, '当前问卷还有未完成的AI作答任务，请稍后再试');

        $plan_count = Db::name('plan')->where(['question_id' => $id, 'is_del' => 0])->count();
        if ($plan_count) adminReturn(2, '当前问卷已存在AI作答任务，不可再次作答');

        $all_answer_count = $info['all_answer_count'];
        $single_answer_time = $info['single_answer_time'];
        $user_rule = $info['user_rule'];

        $plan_data = [];
        // 单次向AI索要的答案数量
        $system_single_answer_count = C('SYSTEM_SINGLE_ANSWER_COUNT');
        $plan_count = ceil($all_answer_count / $system_single_answer_count);
        $time = time();

        $question = extractOpenEndedQuestions(json_decode($info['question'], true));
        $answer_prompt = '关于' . $info['title'] . '的调查问卷，请你回复我以下几个问题：';
        if ($question) {
            foreach ($question as $k => $v) {
                $answer_prompt .= PHP_EOL . ($k + 1) . '. ' . $v;
            }
        }

        for ($i = 0; $i < $plan_count; $i++) {
            if ($all_answer_count > $system_single_answer_count) {
                if ($i + 1 < $plan_count) {
                    // 不是最后一次
                    $answer_count = $system_single_answer_count;
                } else {
                    // 最后一次
                    $answer_count = $all_answer_count % $system_single_answer_count == 0 ? $system_single_answer_count : $all_answer_count % $system_single_answer_count;
                }
            } else {
                $answer_count = $all_answer_count;
            }

            $prompt_template = C('PROMPT_TEMPLATE');// AI提问模板
            $prompt_rule_str = C('PROMPT_RULE');

            $prompt_rule = str_replace("{{ question }}", $answer_prompt, $prompt_template);

            $prompt_rule .= PHP_EOL . $prompt_rule_str;

            $prompt_rule = str_replace("{{ answer_count }}", $answer_count, $prompt_rule);

            $plan_data[] = [
                'user_id' => session('id'),
                'question_id' => $id,
                'prompt' => $prompt_rule,
                'answer_count' => $answer_count,
                'question_rule' => json_encode(['all_answer_count' => $all_answer_count, 'single_answer_time' => $single_answer_time, 'user_rule' => $user_rule], JSON_UNESCAPED_UNICODE),
                'create_time' => $time
            ];
        }

        $res = Db::name('plan')->insertAll($plan_data);
        if ($res) {
            startPs1();

            adminReturn(1, 'AI作答中，请稍后查看结果');
        } else {
            adminReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * AI答题进度列表
     * */
    public function planList()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '问卷ID缺失');

        $running_plan_id = 0;
        $list = Db::name('plan')->where(['question_id' => $id, 'is_del' => 0])->order('id asc')->paginate()->each(function ($val) use (&$running_plan_id) {
            if ($val['status'] == 2) $running_plan_id = $val['id'];
            return $val;
        });

        $this->assign('running_plan_id', $running_plan_id);

        // 检查ChromeDriver是否启动
        $this->assign('chromeDriverStatus', checkChromeDriverStatus());
        // 检查SeleniumWebDriver是否启动
        $this->assign('seleniumWebDriverStatus', checkSeleniumWebDriverStatus());

        $question_info = Db::name('question')->where(['id' => $id])->find();
        $this->assign('question_title', $question_info['title']);
        $this->assign('question_status', $question_info['status']);
        $this->assign('all_answer_count', $question_info['all_answer_count']);

        $all_complete_count = Db::name('plan')->where(['question_id' => $id, 'is_del' => 0])->sum('complete_count');
        $this->assign('all_complete_count', $all_complete_count);

        $this->assign('list', $list);
        $this->assign('title', 'AI答题进度列表');

        return $this->view->fetch();
    }

    /**
     * AI重新作答
     * */
    public function againAnswer()
    {
        $input = Request()->param();

        set_time_limit(5); // 设置请求最大执行时间为 5 秒

        $id = $input['id'];

        if (empty($id)) adminReturn(2, '任务ID缺失');

        $info = Db::name('plan')->where(['id' => $id])->find();
        if (empty($info)) adminReturn(2, '任务不存在');

        Db::startTrans();
        try {
            Db::name('plan')->where(['id' => $id])->update(['is_send' => 0, 'send_time' => 0, 'is_complete' => 0, 'complete_time' => 0, 'complete_count' => 0]);
            if ($info['is_complete'] == 1) Db::name('message')->where(['plan_id' => $id])->delete();

            startPs1();

            Db::commit();
            adminReturn(1, '操作成功，请稍后查看AI答题结果');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 删除AI答题任务
     * */
    public function delPlan()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) adminReturn(2, '任务ID缺失');

        Db::startTrans();
        try {
            Db::name('plan')->where(['id' => $id])->setField('is_del', 1);
            Db::name('message')->where(['plan_id' => $id])->delete();

            Db::commit();
            adminReturn(1, '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '删除失败');
        }
    }

    public function againRunning()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) adminReturn(2, '任务ID缺失');

        $res = restartAllServers($id);

        if($res['chromedriver']['status'] != 'success') apiReturn(2, 'ChromeDriver服务启动失败，请重试');
        if($res['seleniumServer']['status'] != 'success') apiReturn(2, 'SeleniumWebDriver服务启动失败，请重试');

        apiReturn(1, '操作成功，大约5分钟之后查看该数据是否正常被运行');
    }

    /**
     * AI作答详情
     * */
    public function aiAnswerDetail()
    {
        $input = Request()->param();

        $id = $input['id'];
        $index = $input['index'] ? : 0;

        if (empty($id)) adminReturn(2, '问卷ID缺失');

        $info = Db::name('question')->where(['id' => $id])->find();
        $info['question'] = json_decode($info['question'], true);
        $this->assign('info', $info);

        $info = Db::name('plan p')->join('auto_message m', 'p.id = m.plan_id', 'LEFT')
            ->field('p.id,p.question_id,p.answer_count,p.answer_count,m.prompt,p.question_rule,m.text,m.create_time')
            ->where(['p.id' => $id, 'p.is_del' => 0])
            ->find();

        if ($info) {
            $question = Db::name('question')->where(['id' => $info['question_id']])->find();
            $info['title'] = $question['title'];
            $info['question'] = json_decode($question['question'], true);
            //            $info['prompt'] = nl2br(htmlspecialchars($info['prompt']));
            //            $info['question'] = json_decode($info['prompt'], true);
            $info['question_rule'] = json_decode($info['question_rule'], true);

            $user_rule = json_decode($info['question_rule']['user_rule'], true);
            $this->assign('user_rule', $user_rule);

            $string = $info['text'];  // 获取原始字符串
            // 使用正则表达式将类似 "1|2|4" 这样的多选答案转换成数组
            $string = preg_replace_callback('/(\d+(\|\d+)+)/', function ($matches) {
                // 将多选项用逗号分隔并用方括号括起来变成数组格式
                return '[' . str_replace('|', ',', $matches[0]) . ']';
            },                              $string);

            // 将字符串转换为PHP数组
            $answer = json_decode($string, true);
        } else {
            adminReturn(2, '数据不存在或已删除');
        }

        $this->assign('ai_answer', json_encode($answer, JSON_UNESCAPED_UNICODE));
        $this->assign('id', $id);
        $this->assign('index', $index);
        $this->assign('info', $info);
        $this->assign('question', json_encode($info['question'], JSON_UNESCAPED_UNICODE));
        $this->assign('title', 'AI作答详情');
        return $this->view->fetch();
    }

    /**
     * 删除问卷
     * */
    public function delQuestion()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '问卷ID缺失');

        $info = Db::name('question')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                $data = [
                    'is_del' => 1,
                    'status' => 0,
                    'update_time' => time()
                ];
                Db::name('question')->where(['id' => $id])->update($data);

                $plan_list = Db::name('plan')->where(['question_id' => $id])->select();
                if ($plan_list) {
                    Db::name('plan')->where(['question_id' => $id])->setField('is_del', 1);
                    $plan_ids = array_column($plan_list, 'id');

                    $message_count = Db::name('message')->where(['plan_id' => ['in', $plan_ids]])->count();
                    if ($message_count) Db::name('message')->where(['plan_id' => ['in', $plan_ids]])->delete();
                }

                Db::commit();
                adminReturn(1, '删除成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '删除失败' . $e->getMessage());
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 文章列表
     * */
    public function articleList()
    {
        $list = Db::name('article')->order('sort asc')->paginate()->each(function ($v) {
            $type_info = Db::name('article_type')->where(['id' => $v['type_id']])->find();
            $v['type_name'] = $type_info['name'];

            return $v;
        });

        $type_list = Db::name('article_type')->select();

        $this->assign('list', $list);
        $this->assign('type_list', $type_list);
        $this->assign('title', '文章列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章
     * */
    public function doArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $title = $input['title'];
            $vice_title = $input['vice_title'];
            $img = $input['img'];
            $type_id = $input['type_id'];
            $user_id = $input['user_id'];
            $sort = $input['sort'];
            $content = $input['content'];

            if (empty($title)) adminReturn(2, '请输入标题');
            if (empty($vice_title)) adminReturn(2, '请输入副标题');
            if (empty($img)) adminReturn(2, '请上传封面图');
            if (empty($type_id)) adminReturn(2, '请选择分类');
            if (empty($user_id)) adminReturn(2, '请选择作者');
            if (empty($content)) adminReturn(2, '请输入内容');

            $time = time();
            $data = [
                'title' => $title,
                'vice_title' => $vice_title,
                'img' => $img,
                'type_id' => $type_id,
                'user_id' => $user_id,
                'sort' => $sort,
                'content' => $content
            ];

            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('article')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('articleList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('article')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('articleList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id > 0) {
                $info = Db::name('article')->where(['id' => $id])->find();
            }

            $type_list = Db::name('article_type')->select();

            $user_list = Db::name('user')->select();

            $this->assign('title', ($id > 0 ? '编辑' : '新增') . '文章');
            $this->assign('info', $info);
            $this->assign('type_list', $type_list);
            $this->assign('user_list', $user_list);

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章
     * */
    public function delArticle()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '文章ID缺失');

        $info = Db::name('article')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('article')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 删除文章分类
     * */
    public function delGoodsType()
    {
        $input = Request()->param();

        $id = $input['id'];
        $pid = $input['pid'];

        if (empty($id)) adminReturn(2, '分类ID缺失');

        Db::startTrans();
        try {
            $info = Db::name('goods_type')->where(['id' => $id])->find();
            if ($info) {
                Db::name('goods_type')->where(['id' => $id])->delete();
                if ($pid == 0) Db::name('goods_type')->where(['pid' => $id])->delete();

                Db::commit();
                adminReturn(1, '删除成功');
            } else {
                Db::rollback();
                adminReturn(2, '数据不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * banner列表
     */
    public function bannerList()
    {
        $list = Db::name('banner')->paginate();

        $this->assign('list', $list);
        $this->assign('title', 'banner列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 banner
     * */
    public function doBanner()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $img = $input["img"];
            $type = $input["type"];
            $to_id = $input["to_id"];

            if (empty($img)) adminReturn(2, '请上传banner图');

            $data = [
                "img" => $img,
                "type" => $type,
                'to_id' => $to_id
            ];

            if ($id > 0) {
                $res = Db::name('banner')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '编辑banner失败或未编辑');
                }
            } else {
                $res = Db::name('banner')->insert($data);
                if ($res) {
                    adminReturn(1, '新增banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '新增banner失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('banner')->where(['id' => $id])->find();

            $goods_list = Db::name('goods')->field('id,name')->select();
            $this->assign('goods_list', $goods_list);
            $this->assign('goods_list_obj', json_encode($goods_list, JSON_UNESCAPED_UNICODE));

            $article_list = Db::name('article')->field('id,title name')->select();
            $this->assign('article_list_obj', json_encode($article_list, JSON_UNESCAPED_UNICODE));

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . 'banner');

            return $this->view->fetch();
        }
    }

    /**
     * 删除banner
     * */
    public function delBanner()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'bannerID缺失');

        $info = Db::name('banner')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('banner')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 公告列表
     */
    public function msgList()
    {
        $input = Request()->param();

        $title = $input['title'];
        $where["type"] = 3;
        if ($title) $where['title'] = ["like", '%' . $title . '%'];
        $list = Db::name('msg')->where($where)->order('create_time desc')->paginate();


        $this->assign('list', $list);

        $this->assign('title', '公告列表');

        return $this->fetch();
    }

    /**
     * 新增/编辑 公告
     */
    public function doMsg()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input['id'];
            $title = $input["title"];
            $content = $input["content"];

            if (empty($title)) adminReturn(2, "请输入标题");
            if (empty($content)) adminReturn(2, "请填写公告内容");

            if ($id) {
                $data = [
                    'title' => $title,
                    'content' => $content
                ];

                $res = Db::name('msg')->where(['id' => $id])->update($data);
            } else {
                $data = [
                    "user_id" => 0,
                    "title" => $title,
                    "content" => $content,
                    "type" => 3,
                    "look_count" => 0,
                    "create_time" => time()
                ];

                $res = Db::name('msg')->insert($data);
            }

            if ($res) {
                adminReturn(1, ($id ? '编辑' : '新增') . '公告成功', url('msgList'));
            } else {
                adminReturn(2, ($id ? '编辑' : '新增') . '公告失败');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('msg')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '公告详情' : '新增公告'));

            return $this->view->fetch();
        }
    }

    /**
     * 删除公告
     */
    public function delMsg()
    {
        $input = Request()->param();

        $id = $input["id"];

        if ($id > 0) {
            $res = Db::name('msg')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除公告成功', url('msgList'));
            } else {
                adminReturn(2, '删除公告失败');
            }
        }
    }

    /**
     * 意见反馈
     */
    public function feedbackList()
    {
        $input = Request()->param();

        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $where["a.id"] = ["gt", "0"];

        if (!empty($start_time) && empty($end_time)) {
            $where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('feedback a')->field("a.*,b.username")->join('user b', "a.user_id = b.id", "left")
            ->where($where)->order('a.create_time desc')->paginate();
        $this->assign('list', $list);

        $this->assign('title', '意见反馈列表');

        return $this->fetch();
    }

}
